import ElementPlus from 'element-plus';
<template>
  <div class="form-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="top"
    >
      <el-form-item label="事件名称" prop="eventName">
        <el-input v-model="formData.eventName" placeholder="请输入事件名称" />
      </el-form-item>
      <el-form-item label="事件状态" prop="eventStatus">
        <el-input v-model="formData.eventStatus" placeholder="请输入事件状态" />
      </el-form-item>

      <el-form-item label="责任人信息" prop="person">
        <el-button type="primary" @click="addPerson" class="add-person-btn">
          添加责任人
        </el-button>
        <el-table :data="formData.person" style="width: 100%" border>
          <el-table-column label="责任人姓名" prop="name">
            <template #default="scope">
              <el-form-item
                :prop="'person.' + scope.$index + '.name'"
                :rules="rules.personName"
                class="table-form-item"
              >
                <el-input
                  v-model="scope.row.name"
                  placeholder="请输入责任人姓名"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="责任人年龄" prop="age">
            <template #default="scope">
              <el-form-item
                :prop="'person.' + scope.$index + '.age'"
                :rules="rules.personAge"
                class="table-form-item"
              >
                <el-input
                  v-model.number="scope.row.age"
                  placeholder="请输入责任人年龄"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                @click="removePerson(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="result-display">
      <h3>表单提交数据预览:</h3>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

// --- 类型定义 ---
interface Person {
  name: string;
  age: number | ""; // 允许为空字符串以便输入框清空
}

interface FormData {
  eventName: string;
  eventStatus: string;
  person: Person[];
}

// --- 组件状态和逻辑 ---
const formRef = ref<FormInstance>();

const formData = reactive<FormData>({
  eventName: "",
  eventStatus: "",
  person: [{ name: "张三", age: 30 }],
});

// 自定义校验器，确保 person 数组不为空
const validatePerson = (rule: any, value: any, callback: any) => {
  if (!value || value.length === 0) {
    callback(new Error("请至少添加一位责任人"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  eventName: [{ required: true, message: "请输入事件名称", trigger: "blur" }],
  eventStatus: [{ required: true, message: "请输入事件状态", trigger: "blur" }],
  person: [{ required: true, validator: validatePerson, trigger: "change" }],
  // 表格内部的校验规则
  personName: [
    { required: true, message: "请输入责任人姓名", trigger: "blur" },
  ],
  personAge: [
    { required: true, message: "请输入责任人年龄", trigger: "blur" },
    { type: "number", message: "年龄必须是数字", trigger: "blur" },
  ],
});

// --- 方法 ---

/**
 * 添加一个新的责任人记录
 */
const addPerson = () => {
  formData.person.push({
    name: "",
    age: "",
  });
};

/**
 * 根据索引删除一个责任人记录
 * @param index 要删除的记录的索引
 */
const removePerson = (index: number) => {
  formData.person.splice(index, 1);
};

/**
 * 提交表单
 */
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!", formData);
      ElMessage.success("提交成功!");
    } else {
      console.log("error submit!", fields);
      ElMessage.error("表单校验失败，请检查输入项");
    }
  });
};

/**
 * 重置表单
 */
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  // 手动清空表格数据
  formData.person = [];
};
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.add-person-btn {
  margin-bottom: 15px;
}

.table-form-item {
  margin-bottom: 0; /* 移除表格内 el-form-item 的默认下边距 */
}

/* 移除校验失败时的红色星号对布局的影响 */
.el-form-item.is-error .el-input {
  margin-bottom: 18px;
}

.result-display {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border: 1px dashed #e0e0e0;
  border-radius: 4px;
}

.result-display h3 {
  margin-top: 0;
}

pre {
  font-family: "Courier New", Courier, monospace;
  font-size: 14px;
  color: #333;
}
</style>
